﻿using IcsSEMCtrl.Event;
using IcsSEMCtrl.Global;
using IcsSEMCtrl.Service.Alarm;
using IcsSEMCtrl.Service.Logger;
using IcsSEMCtrl.Util.Client;
using Lifter;
using Lifter.Device;
using Lifter.Device.Service;
using Lifter.Global.Device;
using Lifter.Utility;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using TKT.Lifter.CIM.Lifter.Device.Service;
using TKT.Lifter.CIM.Lifter.Event.Lifter;
using TKT.Lifter.CIM.Lifter.Global;
using TKT.Lifter.CIM.Lifter.Gui.Monitor.Popups;

namespace TKT.Lifter.CIM.Lifter.Gui.Monitor.Panels
{
	public partial class UserManageControl : UserControl
    {
		private Thread threadSearch = null;
		List<UserOperationDao> AllRows = new List<UserOperationDao>();
		private delegate void delegateUpdateAlarmShow();
		DateTimeConverter dateTimeConverter = new DateTimeConverter();
		public delegate void page();
		private delegate void AddDataGrid(List<UserOperationDao> readString);
		public static UserManageControl userManageControl;
		private List<EcpAlarm> alarmsPage = new List<EcpAlarm>();
		private List<EcpAlarm> m_BufferAlarms = new List<EcpAlarm>();
		UserManager userManager = UserManager.GetUserManager();
		
		public List<EcpAlarm> Alarms { get => alarmsPage; set => alarmsPage = value; }
		public UserManageControl()
        {
            try
            {
                InitializeComponent();
                InitializeUserOprDataGrid();
                InitializeUserManageDataGrid();
                InitializeAlarmDataGrid();
                AlarmShowEventAdapter alarmShowEventAdapter = new AlarmShowEventAdapter();
                userManageControl = this;
                this.UserOprStartTime.Text = "";
                this.UserOprEndTime.Text = "";
            }
            catch (Exception e)
            {
				Console.WriteLine(e.Message);
				//可添加Log
            }
        }
		private class AlarmShowEventAdapter : ECPEventAdapter
		{
			public AlarmShowEventAdapter()
			{
				base.Subscribe();
			}
			public override string GetSubscriptionSubject()
			{
				return AlarmShowEvent.FormSubject("*");
			}

			public override void ReceiveECPEvent(ECPEvent ecpEvent)
			{
				userManageControl.UpdateAlarmShowEvent(ecpEvent);
			}
		}
		private void UpdateAlarmShowEvent(ECPEvent ecpEvent)
		{
			try
			{
				AlarmShowEvent alarmShowEvent = (AlarmShowEvent)ecpEvent;
				this.Alarms = alarmShowEvent.Alarms1;
				this.BeginInvoke(new delegateUpdateAlarmShow(UpdateAlarms));
			}
			catch (Exception ex)
			{
				Console.WriteLine(DateTime.Now + "报错信息:" + ex.Message);
			}
		}
		private void UpdateAlarms()
        {
			try
			{
				this.dgvAlarmShow.Rows.Clear();
				int index = 0;

				List<EcpAlarm> list;
				if (LifterMainForm.PlaybackMode)
                {
                    list = this.m_BufferAlarms;
                }
                else
                {
                    list = this.Alarms;
                }

				if(list != null && list.Count() > 0)
                {
					this.dgvAlarmShow.RowCount = list.Count();
					foreach (EcpAlarm alarm in list)
					{
						this.dgvAlarmShow.Rows[index].Cells[0].Value = alarm.ALID;
						this.dgvAlarmShow.Rows[index].Cells[1].Value = alarm.ALCD;
						this.dgvAlarmShow.Rows[index].Cells[2].Value = alarm.ALTX;
						this.dgvAlarmShow.Rows[index].Cells[3].Value = alarm.Cause;
						this.dgvAlarmShow.Rows[index].Cells[4].Value = alarm.Alsl;
						index++;
					}
				}               
            }
            catch (Exception ex)
            {
				LogHelper.loggerError("在[UpdateAlarms]方法中更新报警信息报错",ex);
            }

        }
		public void UpdateAlarms(List<EcpAlarm> alarms)
		{
			this.dgvAlarmShow.Rows.Clear();
			int index = 0;
            if (alarms != null && alarms.Count > 0)
            {
				this.dgvAlarmShow.RowCount = alarms.Count();
				foreach (EcpAlarm alarm in alarms)
				{
					this.dgvAlarmShow.Rows[index].Cells[0].Value = alarm.ALID;
					this.dgvAlarmShow.Rows[index].Cells[1].Value = alarm.ALCD;
					this.dgvAlarmShow.Rows[index].Cells[2].Value = alarm.ALTX;
					this.dgvAlarmShow.Rows[index].Cells[3].Value = alarm.Cause;
					this.dgvAlarmShow.Rows[index].Cells[4].Value = alarm.Alsl;
					index++;
				}
			}
		}
		private void InitializeUserOprDataGrid()
		{
			try
			{
				this.dgvUserOpr.AllowUserToAddRows = true;
				this.dgvUserOpr.Columns.Add(new DataGridViewTextBoxColumn());
				this.dgvUserOpr.Columns.Add(new DataGridViewTextBoxColumn());
				this.dgvUserOpr.Columns.Add(new DataGridViewTextBoxColumn());
				this.dgvUserOpr.Columns.Add(new DataGridViewTextBoxColumn());
				this.dgvUserOpr.Columns[0].HeaderText = "序号";
				this.dgvUserOpr.Columns[1].HeaderText = "用户名";
				this.dgvUserOpr.Columns[2].HeaderText = "事件内容";
				this.dgvUserOpr.Columns[3].HeaderText = "操作时间";

				this.dgvUserOpr.RowsDefaultCellStyle.WrapMode = DataGridViewTriState.True;
				this.dgvUserOpr.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);

				//设置分页控件每页数量
				UserOprPagination.PageSize = 10;
			}
			catch (Exception)
			{
			}
		}
		private void InitializeUserManageDataGrid()
		{
			try
			{
				this.dgvUsers.AllowUserToAddRows = true;
				this.dgvUsers.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
				this.dgvUsers.Columns.Add(new DataGridViewTextBoxColumn());
				this.dgvUsers.Columns.Add(new DataGridViewTextBoxColumn());
				this.dgvUsers.Columns.Add(new DataGridViewTextBoxColumn());
				this.dgvUsers.Columns[0].HeaderText = "用户名";
				this.dgvUsers.Columns[1].HeaderText = "用户密码";
				this.dgvUsers.Columns[2].HeaderText = "用户权限";

				this.dgvUsers.Columns[0].Width = 260;
				this.dgvUsers.Columns[1].Width = 200;
				this.dgvUsers.Columns[2].Width = 100;

				this.dgvUsers.RowsDefaultCellStyle.WrapMode = DataGridViewTriState.False;
				this.dgvUsers.AllowUserToAddRows = false;
				this.dgvUsers.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);

				//设置分页控件每页数量
				UserOprPagination.PageSize = 10;
			}
			catch (Exception)
			{
			}
		}
		private void InitializeAlarmDataGrid()
		{
			try
			{
				this.dgvAlarmShow.AllowUserToAddRows = false;
				this.dgvAlarmShow.Columns.Add(new DataGridViewTextBoxColumn());
				this.dgvAlarmShow.Columns.Add(new DataGridViewTextBoxColumn());
				this.dgvAlarmShow.Columns.Add(new DataGridViewTextBoxColumn());
				this.dgvAlarmShow.Columns.Add(new DataGridViewTextBoxColumn());
				this.dgvAlarmShow.Columns.Add(new DataGridViewTextBoxColumn());
				this.dgvAlarmShow.Columns[0].HeaderText = "报警ID";
				this.dgvAlarmShow.Columns[1].HeaderText = "报警代码";
				this.dgvAlarmShow.Columns[2].HeaderText = "报警内容";
				this.dgvAlarmShow.Columns[3].HeaderText = "造成原因";
				this.dgvAlarmShow.Columns[4].HeaderText = "解警措施";
				this.dgvAlarmShow.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
			}
			catch (Exception)
			{
			}
		}

		private void btUserOprSearch_Click(object sender, EventArgs e)
        {
			AllRows.Clear();
			if (this.threadSearch == null)
			{
				this.threadSearch = new Thread(new ThreadStart(this.UserOprRead));
			}
			if (this.threadSearch.ThreadState != ThreadState.Running)
			{
				if (this.threadSearch.ThreadState == ThreadState.Stopped)
				{
					this.threadSearch = new Thread(new ThreadStart(this.UserOprRead));
					this.threadSearch.Start();
				}
				else
				{
					if (this.threadSearch.ThreadState == ThreadState.Stopped)
					{
						this.threadSearch.Start();
					}
					else
					{
						if (this.threadSearch.ThreadState == ThreadState.Unstarted)
						{
							this.threadSearch.Start();
						}
					}
				}
			}
		}
		private void UserOprRead()
		{
			try
			{
				string startTime = this.UserOprStartTime.Text;
				string endTime = this.UserOprEndTime.Text;
				string keyWord = this.tbUserKeyWord.Text;
				UserManager userManager = UserManager.GetUserManager();
				this.AllRows = userManager.GetUserOperation(startTime, endTime, keyWord);
				//设置分页信息
				//设置分页控件总数
				UserOprPagination.BeginInvoke(new page(() => {
					{
						UserOprPagination.TotalCount = AllRows.Count();
						UserOprPagination.ActivePage = 1;
					}
				}));
			}
			catch (Exception ex)
			{
				PopupNotice.DialogPopups("查询失败，错误代码 :" + ex.Message, "Query failed with error code: " + ex.Message, enumPopupsType.Error);
				LogHelper.loggerError("在[UserOprRead]方法中报错，查询失败", ex);
				return;
			}
		}

        private void UserOprPagination_PageChanged(object sender, object pagingSource, int pageIndex, int count)
        {
			if (UserOprPagination.TotalCount >= pageIndex * count)
			{
				List<UserOperationDao> rows = AllRows.GetRange((pageIndex - 1) * count, count);
				LoadData(rows);
			}
			else
			{
				List<UserOperationDao> rows = AllRows.GetRange((pageIndex - 1) * count, (UserOprPagination.TotalCount - ((pageIndex - 1) * count)));
				LoadData(rows);
			}
		}
		public void LoadData(List<UserOperationDao> rows)
		{
			dgvUserOpr.Rows.Clear();
			base.BeginInvoke(new UserManageControl.AddDataGrid(this.AddLogData), rows);
		}
		private void AddLogData(List<UserOperationDao> userOperations)
		{
			try
			{
				int index = 0;
				int rowNum = 1;
				if (userOperations != null && userOperations.Count() > 0)
				{
					this.dgvUserOpr.RowCount = userOperations.Count();
					foreach (UserOperationDao userOperationDao in userOperations)
					{
						this.dgvUserOpr.Rows[index].Cells[0].Value = rowNum;
						this.dgvUserOpr.Rows[index].Cells[1].Value = userOperationDao.UserName;
						this.dgvUserOpr.Rows[index].Cells[2].Value = userOperationDao.EventDesc;
						this.dgvUserOpr.Rows[index].Cells[3].Value = userOperationDao.EventTime;
						index++;
						rowNum++;
					}
				}
			}
            catch(Exception ex)
            {
				throw ex;
            }
			this.UserOprStartTime.Text = "";
			this.UserOprEndTime.Text = "";
		}

        private void btSearchUser_Click(object sender, EventArgs e)
        {
			List<UserDao> userLists = new List<UserDao>();
			if (string.IsNullOrEmpty(this.tbUserName.Text))
            {
                userLists = userManager.SelectAll();
            }
            else
            {
				userLists = userManager.Select(this.tbUserName.Text);
			}
			if (userLists.Count == 0)
			{
				PopupNotice.DialogPopups("查询用户数据为空，请检查！！", "The query user data is empty, please check!!!", enumPopupsType.Warning);
				return;
			}
			else
			{
				int index = 0;
				this.dgvUsers.RowCount = userLists.Count();
				foreach (UserDao item in userLists)
                {
					this.dgvUsers.Rows[index].Cells[0].Value = item.USERID1;
					this.dgvUsers.Rows[index].Cells[1].Value = item.USERPASSWORD1;
					this.dgvUsers.Rows[index].Cells[2].Value = item.PRIVILEGE1;
					index++;
				}
			}
		}

        private void btAddUser_Click(object sender, EventArgs e)
        {
			//判断输入框是否为空
            if (string.IsNullOrEmpty(this.tbUserName.Text))
            {
				PopupNotice.TipsPopups("用户名不能为空", "User name cannot be empty");
				return;
            }
			if (string.IsNullOrEmpty(this.tbRePassWord.Text))
			{
				PopupNotice.TipsPopups("确认密码输入不能为空", "Confirm password input cannot be empty");
				return;
			}
			if (string.IsNullOrEmpty(this.tbPassword.Text))
			{
				PopupNotice.TipsPopups("密码输入不能为空", "Password input cannot be empty");
				return;
			}
			if (string.IsNullOrEmpty(this.tbUserPri.Text))
			{
				PopupNotice.TipsPopups("权限输入不能为空", "Power input cannot be empty");
				return;
			}
            if (!this.tbRePassWord.Text.Equals(this.tbPassword.Text))
            {
				PopupNotice.TipsPopups("密码与确认密码输入不一致，请检查！！", "The password and confirmation password input do not match. Please check!!");
				return;
			}
			//判断添加的用户是否已经存在
			List<UserDao> lists = userManager.Select(this.tbUserName.Text);
			if (lists.Count != 0)
			{
				PopupNotice.DialogPopups("添加失败，此用户数据已存在，请检查！！", "Adding failed, this user data already exists, please check!!", enumPopupsType.Warning);
				return;
			}
            else
            {
				 int code = userManager.Insert(this.tbUserName.Text, this.tbPassword.Text, this.tbUserPri.Text);
                if (code != 0)
                {
					LifterSEM LftSem = (LifterSEM)Naming.GetDeviceManager().GetDevice();
					PopupNotice.DialogPopups("用户添加成功", "User added successfully", enumPopupsType.OK);
					LogHelper.operationLogger(string.Format("用户[{0}]进行了添加用户操作", LftSem.UserName));
					LftSem.InsertUserOperation(LftSem.UserName, string.Format("用户[{0}]进行了添加用户操作", LftSem.UserName));
					List<UserDao> userDaos = userManager.SelectAll();
					int index = 0;
					this.dgvUsers.RowCount = userDaos.Count();
					foreach (UserDao item in userDaos)
					{
						this.dgvUsers.Rows[index].Cells[0].Value = item.USERID1;
						this.dgvUsers.Rows[index].Cells[1].Value = item.USERPASSWORD1;
						this.dgvUsers.Rows[index].Cells[2].Value = item.PRIVILEGE1;
						index++;
					}
					this.clear();
				}
                else
                {
					PopupNotice.DialogPopups("用户添加失败", "User add failed", enumPopupsType.Error);
				}
            }
		}

        private void btModifyUser_Click(object sender, EventArgs e)
        {
            try
            {
				//判断输入框是否为空
				if (string.IsNullOrEmpty(this.tbUserName.Text))
				{
					PopupNotice.TipsPopups("用户名不能为空", "User name cannot be empty");
					return;
				}
				//判断用户是否存在
				List<UserDao> lists = userManager.Select(this.tbUserName.Text);
				string password = lists[0].USERPASSWORD1;
				int pri = lists[0].PRIVILEGE1;
				if (lists.Count == 0)
				{
					PopupNotice.DialogPopups("修改失败，此用户不存在，请检查！！", "Modification failed, this user does not exist, please check!!", enumPopupsType.Error);
					return;
				}
				else
				{
					if (!string.IsNullOrEmpty(this.tbPassword.Text))
					{
						password = this.tbPassword.Text;
					}
					if (!string.IsNullOrEmpty(this.tbUserPri.Text))
					{
						pri = Convert.ToInt32(this.tbUserPri.Text);
					}
					int code = userManager.Update(this.tbUserName.Text, password, pri);
					if (code != 0)
					{
						PopupNotice.DialogPopups("修改用户成功", "Successfully modified user", enumPopupsType.OK);
						LifterSEM LftSem = (LifterSEM)Naming.GetDeviceManager().GetDevice();
						LogHelper.operationLogger(string.Format("用户[{0}]进行了更新用户操作", LftSem.UserName));
						LftSem.InsertUserOperation(LftSem.UserName, string.Format("用户[{0}]进行了更新用户操作", LftSem.UserName));
						List<UserDao> userDaos = userManager.SelectAll();
						int index = 0;
						this.dgvUsers.RowCount = userDaos.Count();
						foreach (UserDao item in userDaos)
						{
							this.dgvUsers.Rows[index].Cells[0].Value = item.USERID1;
							this.dgvUsers.Rows[index].Cells[1].Value = item.USERPASSWORD1;
							this.dgvUsers.Rows[index].Cells[2].Value = item.PRIVILEGE1;
							index++;
						}
						this.clear();
					}
					else
					{
						PopupNotice.DialogPopups("修改用户失败", "User Modify failed", enumPopupsType.Error);
					}
				}
			}
            catch (Exception ex)
            {
				UIMessageDialog.ShowMessageDialog(ex.Message, UILocalize.WarningTitle, showCancelButton: false, UIStyle.Red, false, false);
			}
		}

        private void btDeleteUser_Click(object sender, EventArgs e)
        {
			try
			{
				//判断输入框是否为空
				if (string.IsNullOrEmpty(this.tbUserName.Text))
				{
					PopupNotice.TipsPopups("用户名不能为空", "User name cannot be empty");
					return;
				}
				//判断用户是否存在
				List<UserDao> lists = userManager.Select(this.tbUserName.Text);
				if (lists.Count == 0)
				{
					PopupNotice.DialogPopups("删除失败，此用户不存在，请检查！！", "Delete failed, this user does not exist, please check!!", enumPopupsType.Error);
					return;
				}
				else
				{
					int code = userManager.Delete(this.tbUserName.Text);
					if (code != 0)
					{
						PopupNotice.DialogPopups("删除用户成功", "Successfully delete user", enumPopupsType.OK);
						LifterSEM LftSem = (LifterSEM)Naming.GetDeviceManager().GetDevice();
						LogHelper.operationLogger(string.Format("用户[{0}]进行了删除用户操作", LftSem.UserName));
						LftSem.InsertUserOperation(LftSem.UserName, string.Format("用户[{0}]进行了删除用户操作", LftSem.UserName));
						List<UserDao> userDaos = userManager.SelectAll();
						int index = 0;
						this.dgvUsers.RowCount = userDaos.Count();
						foreach (UserDao item in userDaos)
						{
							this.dgvUsers.Rows[index].Cells[0].Value = item.USERID1;
							this.dgvUsers.Rows[index].Cells[1].Value = item.USERPASSWORD1;
							this.dgvUsers.Rows[index].Cells[2].Value = item.PRIVILEGE1;
							index++;
						}
						this.clear();
					}
					else
					{
						PopupNotice.DialogPopups("删除用户失败", "Delete User failed", enumPopupsType.Error);
					}
				}
			}
			catch (Exception ex)
			{
				UIMessageDialog.ShowMessageDialog(ex.Message, UILocalize.WarningTitle, showCancelButton: false, UIStyle.Red, false, false);
			}
		}

		public void clear()
		{
			this.tbUserName.Text = "";
			this.tbPassword.Text = "";
			this.tbRePassWord.Text = "";
			this.tbUserPri.Text = "";
		}

		public void UpdatePlaybackAlarmData(string alarmString)
		{
			if (!LifterMainForm.PlaybackMode)
			{
				return;
			}
			string[] strArray = alarmString.Split(new char[] { '@' }, StringSplitOptions.RemoveEmptyEntries);
			this.m_BufferAlarms.Clear();
			foreach (var unit in strArray)
			{
				this.m_BufferAlarms.Add(new EcpAlarm(unit));
			}

			this.BeginInvoke(new delegateUpdateAlarmShow(UpdateAlarms));
		}
		/// <summary>
		/// 报警复位
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void btResetAllAlarm_Click(object sender, EventArgs e)
        {
			LifterSEM LftSem = (LifterSEM)Naming.GetDeviceManager().GetDevice();
			LftSem.O_ALARMRESETREQ = true;
			LogHelper.operationLogger(string.Format("用户[{0}]进行了[报警复位]操作",LftSem.UserName));
			LftSem.InsertUserOperation(LftSem.UserName, string.Format("用户[{0}]进行了[报警复位]操作", LftSem.UserName));
		}
		public void Asynchronous()
		{
			var MethInvo = new MethodInvoker(ResetAllAlarm);
			this.BeginInvoke(MethInvo);
		}
		private void ResetAllAlarm()
		{
			LifterSEM LftSem = (LifterSEM)Naming.GetDeviceManager().GetDevice();
			lock (LifterSEM.alarmMonitor)
			{
				LftSem.ReportAlarms.Clear();
			}
			this.alarmsPage.Clear();
			//更新页面报警信息
			this.UpdateAlarms(alarmsPage);
		}
    }
}
